package jc.controller;


import jc.service.http.HttpGetClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import static jc.service.http.Parser.rewriteHtml;


/**
 * Created by ��� on 2015/7/16.
 */

@Controller
@RequestMapping("")
public class ProxyController {

    @Autowired
    HttpGetClient httpGetClient;

    @RequestMapping("/fetch" )
    public ResponseEntity fetch(@RequestParam(value = "targetUrl", required = false) String targetUrl, HttpServletResponse response){

        if (targetUrl == null){
            targetUrl = "http://www.qq.com";
        }




        Map<String, Object> byteResponse = httpGetClient.getByte(targetUrl);
        Map<String, Object> redirectParams = new HashMap<String, Object>();
        redirectParams.put("domain", byteResponse.get("domain"));

        String contentType = (String)byteResponse.get("contentType");
        // Set headers
        final HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.parseMediaType(contentType));

        if ("text/html".equals(byteResponse.get("type"))){


            String pageHtml = null;
            try{
                pageHtml = new String((byte[])byteResponse.get("byte"),(String)byteResponse.get("charset"));

            }catch (UnsupportedEncodingException e){
                e.printStackTrace();
            }

            String rewritePageHtml =rewriteHtml(pageHtml, redirectParams);

            try{
                //这里将网页字符串变成字节编码，必需要编码方式
                byteResponse.put("byte", rewritePageHtml.getBytes((String)byteResponse.get("charset")));

            }catch (UnsupportedEncodingException e){
                e.printStackTrace();
            }


        }

        byte[] bytes = (byte[]) byteResponse.get("byte");



        return new ResponseEntity (bytes, headers, HttpStatus.CREATED);


    }


}
